package widget

import (
	"image/color"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"gitee.com/hanholy1210/fyne_holy/container"
)

type Button struct {
	widget.DisableableWidget

	Text       string
	Icon       fyne.Resource
	OnTapped   func(*Button)
	SwtichType bool

	size       fyne.Size
	text       *canvas.Text
	textSize   float32
	textColor  color.Color
	icon       *canvas.Image
	iconSize   float32
	background *canvas.Rectangle
}

func NewButton(text string, tapped func(*Button)) *Button {
	b := &Button{}
	b.Text = text
	b.OnTapped = tapped
	b.size = fyne.NewSize(theme.Padding(), theme.Padding())
	b.ExtendBaseWidget(b)
	return b
}
func NewButtonWithIcon(text string, icon fyne.Resource, tapped func(*Button)) *Button {
	b := &Button{}
	b.Text = text
	b.Icon = icon
	b.OnTapped = tapped
	b.ExtendBaseWidget(b)
	return b
}
func (b *Button) CreateRenderer() fyne.WidgetRenderer {
	layFore := container.NewHBox()

	if b.Icon != nil {
		b.icon = canvas.NewImageFromResource(b.Icon)
		b.icon.SetMinSize(fyne.NewSize(theme.IconInlineSize(), theme.IconInlineSize()))
		iconSize := b.icon.MinSize()
		if b.iconSize != 0 {
			iconSize = iconSize.Max(fyne.NewSize(b.iconSize, b.iconSize))
		}
		iconLay := container.NewCenter(container.NewSizeMax(iconSize, b.icon))
		layFore.Add(iconLay)
	}
	if b.Text != "" {
		b.text = canvas.NewText(b.Text, theme.Color(theme.ColorNameForeground))
		if b.textSize != 0 {
			b.text.TextSize = b.textSize
		}
		if b.textColor != nil {
			b.text.Color = b.textColor
		}
		textLay := container.NewCenter(b.text)
		layFore.Add(textLay)
	}
	size := layFore.MinSize()
	size = size.Max(b.size)
	b.background = canvas.NewRectangle(theme.Color(theme.ColorNameButton))
	b.background.CornerRadius = 5
	lay := container.NewSizeMax(size, b.background, container.NewCenter(layFore))
	return widget.NewSimpleRenderer(container.NewCenter(lay))
}
func (b *Button) SetSize(w, h float32) *Button {
	b.size = fyne.NewSize(w, h)
	return b
}
func (b *Button) SetTextSize(size float32) *Button {
	b.textSize = size
	return b
}
func (b *Button) SetTextColor(color color.Color) *Button {
	b.textColor = color
	return b
}
func (b *Button) SetIconSize(size float32) *Button {
	b.iconSize = size
	return b
}

func (b *Button) Tapped(_ *fyne.PointEvent) {
	if b.Disabled() {
		return
	}
	b.OnTapped(b)
}
